package com.fowo.api.service.handleWork;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.fowo.api.entity.InventoryList;
import com.fowo.api.inventory.entity.Inventory;
import com.fowo.api.inventory.mapper.InventoryMapper;
import com.fowo.api.inventory.model.*;
import com.fowo.api.inventory.model.form.InventoryExchangeFormVo;
import com.fowo.api.inventory.service.InventoryBusinessService;
import com.fowo.api.mapper.InventoryListMapper;
import com.fowo.api.model.inventory.list.InventoryListCancellationAction;
import com.fowo.api.model.inventory.list.InventoryListVo;
import com.fowo.api.model.inventory.list.subtable.InventoryListSubtableItemVo;
import com.fowo.api.model.inventory.list.subtable.InventoryListSubtableSearchParamPo;
import com.fowo.api.service.InventoryListSubtableService;
import com.fowo.api.service.impl.InventoryListServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class InventoryListCancellation implements InventoryListCancellationAction {

    @Resource
    private InventoryListMapper inventoryListMapper;
    @Resource
    private InventoryListServiceImpl inventoryListService;
    @Resource
    private InventoryBusinessService inventoryBusinessService;

    @Override
    public void run(Long id) throws Exception {
        InventoryListVo inventoryList = inventoryListService.getVoById(id);
        Assert.notNull(inventoryList,"盘点单不存在");

//        InventoryListSubtableSearchParamPo generateInventoryDetailsSearchParamPo = new InventoryListSubtableSearchParamPo();
//        generateInventoryDetailsSearchParamPo.setParentInventoryList(id);
//        List<InventoryListSubtableItemVo> subList = inventoryListSubtableService.search(generateInventoryDetailsSearchParamPo);
        List<InventoryListSubtableItemVo> subList = inventoryList.getGenerateInventoryDetails();
        if(inventoryList.getStatus().equals("2")){ //盘点中的 要释放库存
            // 释放仓库库存
            InventoryExchangeFormVo warehouseFormVo = prepareUnLockWarehouse(inventoryList);
            inventoryBusinessService.exchange(warehouseFormVo);
            //释放仓位库存
            InventoryExchangeFormVo formVo = prepareUnLockInventory(inventoryList);
            inventoryBusinessService.exchange(formVo);
        }
        inventoryList.setStatus("4");
        inventoryListMapper.updateById(inventoryList);
    }

    /**
     * 准备用于 释放库存 的参数
     */
    protected InventoryExchangeFormVo prepareUnLockInventory(InventoryListVo vo) throws Exception {
        InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
        if (ReflectUtil.hasField(InventoryListVo.class, "remark")) {
            formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
        }
        formVo.setFrom(TargetTypeEnum.Normal);
        formVo.setTo(TargetTypeEnum.Normal);
        formVo.setFormNum(vo.getInventoryNumber());
        formVo.setFormOperator(vo.getLastUpdateUser().toString());
        formVo.setDocumentType("盘点释放库存");
        if(ObjectUtils.isEmpty(vo.getWarehouseStock())){
            throw new Exception("出仓库 为空");
        }
        formVo.setFromStockId(vo.getWarehouseStock());
        if(ObjectUtils.isEmpty(vo.getWarehouseStock())){
            throw new Exception("入仓库 为空");
        }
        formVo.setToStockId(vo.getWarehouseStock());
        formVo.setModel(PatternEnum.FIFO);
        for(InventoryListSubtableItemVo inventoryListSubtable : vo.getGenerateInventoryDetails()) {
            SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
            inventoryItem.setId(inventoryListSubtable.getTradeName());
            InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
            exchangeItem.setItem(inventoryItem);
            exchangeItem.setQty(String.valueOf(inventoryListSubtable.getInventory()).equals("null")?BigDecimal.valueOf(0):BigDecimal.valueOf(inventoryListSubtable.getInventory()));
            exchangeItem.setShopId(String.valueOf(inventoryListSubtable.getShop()).equals("null")? null:String.valueOf(inventoryListSubtable.getShop()));
            exchangeItem.setFnSku( String.valueOf(inventoryListSubtable.getFnsku()).equals("null")? null:String.valueOf(inventoryListSubtable.getFnsku()));
            Map<Long,Integer> binIds=new HashMap<>();
            binIds.put(inventoryListSubtable.getShippingSpace(),Integer.parseInt(String.valueOf(inventoryListSubtable.getInventory()).equals("null")? "0":String.valueOf(inventoryListSubtable.getInventory())));
            exchangeItem.setFromBinIds(binIds);
            Map<Long,Integer> toBinIds=new HashMap<>();
            toBinIds.put(inventoryListSubtable.getShippingSpace(),Integer.parseInt(String.valueOf(inventoryListSubtable.getInventory()).equals("null")? "0":String.valueOf(inventoryListSubtable.getInventory())));
            exchangeItem.setToBinIds(toBinIds);
            exchangeItem.setFromBinIdsType(TargetTypeEnum.Lock);
            exchangeItem.setToBinIdsType(TargetTypeEnum.Normal);
            exchangeItem.setCustomId(vo.getId());
            exchangeItem.setCustomBdId(inventoryListSubtable.getId());
            formVo.add(exchangeItem);
        }
        return formVo;
    }

    /**
     * 准备用于 释放库存_仓库 的参数
     */
    protected InventoryExchangeFormVo prepareUnLockWarehouse(InventoryListVo vo)
            throws Exception {
        InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
        if (ReflectUtil.hasField(InventoryListVo.class, "remark")) {
            formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
        }
        formVo.setFrom(TargetTypeEnum.Lock);
        formVo.setTo(TargetTypeEnum.Normal);
        formVo.setFormNum(vo.getInventoryNumber());
        formVo.setDocumentType("盘点释放库存");
        if (ObjectUtils.isEmpty(vo.getLastUpdateUser())) {
            throw new Exception("关联制单人为空");
        }
        formVo.setFormOperator(vo.getLastUpdateUser().toString());
        if (ObjectUtils.isEmpty(vo.getWarehouseStock())) {
            throw new Exception("出仓库 为空");
        }
        formVo.setFromStockId(vo.getWarehouseStock());
        if (ObjectUtils.isEmpty(vo.getWarehouseStock())) {
            throw new Exception("入仓库 为空");
        }
        formVo.setToStockId(vo.getWarehouseStock());
        formVo.setModel(PatternEnum.FIFO);
        for (InventoryListSubtableItemVo inventoryListSubtable : vo.getGenerateInventoryDetails()) {
            SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
            inventoryItem.setId(inventoryListSubtable.getTradeName());
            InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
            exchangeItem.setItem(inventoryItem);
            exchangeItem.setQty(
                    String.valueOf(inventoryListSubtable.getInventory()).equals("null")
                            ? BigDecimal.valueOf(0)
                            : BigDecimal.valueOf(inventoryListSubtable.getInventory())
            );
            exchangeItem.setShopId(
                    String.valueOf(inventoryListSubtable.getShop()).equals("null")
                            ? null
                            : String.valueOf(inventoryListSubtable.getShop())
            );
            exchangeItem.setFnSku(
                    String.valueOf(inventoryListSubtable.getFnsku()).equals("null")
                            ? null
                            : String.valueOf(inventoryListSubtable.getFnsku())
            );
            exchangeItem.setCustomId(vo.getId());
            exchangeItem.setCustomBdId(inventoryListSubtable.getId());
            formVo.add(exchangeItem);
        }
        return formVo;
    }

}
